/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.actions;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.ipo.mm.ejb.entities.Institution;
import org.ipo.mm.ejb.entities.Representative;
import org.ipo.mm.ejb.entities.User;
import org.ipo.mm.ejb.facade.institution.InstitutionFacadeLocal;
import org.ipo.mm.ejb.facade.log.LogFacadeLocal;
import org.ipo.mm.ejb.facade.representative.RepresentativeFacadeLocal;
import org.ipo.mm.web.formbeans.RepresentativeBean;
import org.ipo.mm.web.util.BreadCrumbs;
import org.ipo.mm.web.util.ConstantManager;
import org.ipo.mm.web.util.UTFEncoder;

/**
 *
 * @author makcro
 */
public class RepresentativeAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward actionForward = null;

        if (isCancelled(request)) {
            actionForward = executeCancel(mapping, form, request, response);
        } else {

            User currentUser = (User) request.getSession().getAttribute(ConstantManager.SESSION_USER_PARAM_NAME);
            RepresentativeBean reprForm = (RepresentativeBean) form;

            MessageResources mResources = getResources(request);
            String saveOperaton = mResources.getMessage(getLocale(request), "gen_create");
            String updateOperation = mResources.getMessage(getLocale(request), "gen_update");
            String createInstitution = mResources.getMessage(getLocale(request), "inst_create");
            String confirmOperation = mResources.getMessage(getLocale(request), "gen_confirm_operation");


            String operation = reprForm.getOperation();
            if (saveOperaton.equals(operation) || confirmOperation.equals(operation)) {
                actionForward = executeCreate(mapping, request, response, reprForm, currentUser);
            } else if (updateOperation.equals(operation)) {
                actionForward = executeUpdate(mapping, request, response, reprForm, currentUser);
            } else if (createInstitution.equals(operation)) {

                actionForward = new ActionForward("/protected/dispatch.do?method=showCreateInstForm", true);
                request.getSession().setAttribute(ConstantManager.SESSION_REPR_RESET_FORM, new Boolean(false));
            }

        }


        return actionForward;
    }

    private ActionForward executeCancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        request.getSession().setAttribute(ConstantManager.SESSION_REPR_RESET_FORM, new Boolean(true));

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();
        return actionForward;
    }

    private ActionForward executeCreate(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response, RepresentativeBean reprForm, User currentUser) {


        // if no similars > save representative
        // if similars then show warning
        // if configrm save

        ActionForward forward = null;
        MessageResources mResources = getResources(request);
        String confirmOperation = mResources.getMessage(getLocale(request), "gen_confirm_operation");

        Representative representative = new Representative();

        String instID = reprForm.getInstitution();
        Institution institution = lookupInstitutionFacade().find(Integer.valueOf(instID));
        // check if similar representative already egzists

        List<Representative> similars = lookupRepresentativeFacade().findSimilar(reprForm.getFirstName(), reprForm.getLastName(), institution);

        // if there are similar constacst then user should confirm that he wants to create this one
        if (similars.size() > 0 && !confirmOperation.equals(reprForm.getOperation())) {
            // put it into request so it can be shown on page
            request.setAttribute(ConstantManager.REQUEST_REPRESENTATIVES_SIMILARS, similars);
            forward = mapping.getInputForward();
        } else {
            representative.setEmail(reprForm.getEmail());
            representative.setFax(reprForm.getFax());
            representative.setFirstName(UTFEncoder.encode(reprForm.getFirstName()));
            representative.setFunction(UTFEncoder.encode(reprForm.getFunction()));
            representative.setLastName(UTFEncoder.encode(reprForm.getLastName()));
            representative.setNote(UTFEncoder.encode(reprForm.getNote()));
            representative.setTelephone(reprForm.getTelephone());

            representative.setInstitution(institution);
            representative.setUser(currentUser);

            lookupRepresentativeFacade().create(representative);

            // store obj in request so it can be automatically selected in list
            request.setAttribute(ConstantManager.REQUEST_REPRESENTATIVE_LAST_CREATED, representative);

            //log
            lookupLogFacade().logCreate(currentUser, ConstantManager.REPRESENTATIVE_NAME, representative.getFirstName() + " " + representative.getLastName());

            notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_CREATE, request);
            BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
            bc.pop();
            forward = bc.pop().getActionForward();

            request.getSession().setAttribute(ConstantManager.SESSION_REPR_RESET_FORM, new Boolean(true));
        }



        return forward;


    }

    private ActionForward executeUpdate(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response, RepresentativeBean reprForm, User currentUser) {

        Representative r = (Representative) request.getSession().getAttribute(ConstantManager.SESSION_REPRESENTATIVE_FOR_UPDATE_PN);

        lookupRepresentativeFacade().update(r.getId(),
                UTFEncoder.encode(reprForm.getFirstName()),
                UTFEncoder.encode(reprForm.getLastName()),
                Integer.valueOf(reprForm.getInstitution()),
                reprForm.getTelephone(),
                reprForm.getEmail(),
                reprForm.getFax(),
                UTFEncoder.encode(reprForm.getFunction()),
                UTFEncoder.encode(reprForm.getNote()));

        lookupLogFacade().logUpdate(currentUser, ConstantManager.REPRESENTATIVE_NAME, reprForm.getFirstName() + " " + reprForm.getLastName());
        
        notifyOperatoinStatus(ConstantManager.OPERATION_TYPE_UPDATE, request);

        BreadCrumbs bc = (BreadCrumbs) request.getSession().getAttribute(ConstantManager.SESSION_BREADCRUMB_PARAM_NAME);
        bc.pop();
        ActionForward actionForward = bc.pop().getActionForward();

        request.getSession().setAttribute(ConstantManager.SESSION_REPR_RESET_FORM, new Boolean(true));

        return actionForward;

    }

    private InstitutionFacadeLocal lookupInstitutionFacade() {
        try {
            Context c = new InitialContext();
            return (InstitutionFacadeLocal) c.lookup("java:comp/env/InstitutionFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private RepresentativeFacadeLocal lookupRepresentativeFacade() {
        try {
            Context c = new InitialContext();
            return (RepresentativeFacadeLocal) c.lookup("java:comp/env/RepresentativeFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    private LogFacadeLocal lookupLogFacade() {
        try {
            Context c = new InitialContext();
            return (LogFacadeLocal) c.lookup("java:comp/env/LogFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

     private void notifyOperatoinStatus(String operationMessageKey, HttpServletRequest request) {

        MessageResources mResources = getResources(request);
        String typeEntityName = mResources.getMessage(getLocale(request), ConstantManager.REPRESENTATIVE_ENTITY_NAME_RES_KEY);

        ActionMessages messages = new ActionMessages();
        ActionMessage actionMessage = new ActionMessage(operationMessageKey, typeEntityName);
        messages.add("operation_status", actionMessage);
        saveMessages(request, messages);

    }
    
}
